package stu.aistar.controller;
import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import stu.aistar.config.AlipayConfig;
import stu.aistar.config.SnowConfig;
import stu.aistar.dao.IMovieDao;
import stu.aistar.dao.IUserDao;
import stu.aistar.model.pojo.Movie;
import stu.aistar.model.pojo.Orders;
import stu.aistar.model.pojo.User;
import stu.aistar.model.vo.PayVo;
import stu.aistar.model.vo.SeatVo;
import stu.aistar.service.IOrdersService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/order")
public class OrderController {

    private SeatVo seatVo;
    private Orders orders;
    @Autowired
    private Snowflake snowflake;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IMovieDao movieDao;
    @Autowired
    private  IUserDao userDao;

    @RequestMapping(value = "payorder",produces = "text/html")
    @ResponseBody
    public String payorder(){
        PayVo payVo=new PayVo();
        payVo.setBody(orders.getSeats());
        payVo.setOut_trade_no(orders.getOrdersNo());
        payVo.setPrice(BigDecimal.valueOf(orders.getTotal()));
        payVo.setSubject(orders.getMovieName());
        try {
            String result=AlipayConfig.pay(payVo);
            System.out.println(result);
            return result;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
       return "";
    }
    @GetMapping("seatsinfo")
    @ResponseBody
    public String seatsInfo(SeatVo seatVo1){
        redisTemplate.opsForValue().set("str",seatVo1);
        System.out.println(seatVo1);
        seatVo=seatVo1;
        return "success";
    }
    @GetMapping("/createorder")
    public String createOrder(HttpServletRequest request){
        // 雪花算法生成有序id的方法
        String order_no = snowflake.nextIdStr();
//        String sno = String.format("%tF",new Date());
//        String sno2 = String.format("%tT",new Date());
//        String order_no = sno.replace("-","")+sno2.replace(":","");
       Double total=seatVo.getTotal();
        System.out.println("total:"+total);
       Double price=seatVo.getPrice();
        System.out.println("price:"+price);
       Date time=new Date();
        User user= (User) request.getSession().getAttribute("user");
        User user1=userDao.findUserByPhone(user.getPhone());
        Integer user_id=user1.getId();
        String username=user1.getUsername();
       String movie_name=seatVo.getMovieName();
       String seats=seatVo.getSeatArea();

       orders=new Orders(null,order_no,total,price,time,"待支付",user_id,movie_name,seats,null,null);
        Integer result=ordersService.insertOrders(orders);
        return "redirect:/order/payorder";
    }

    @GetMapping("/userorder")
    public String plan(Model model, Integer userId,Integer sort){
        List<Orders> ordersList= ordersService.findOrdersByUserId(userId);
        if(sort==1){
         ordersList.sort(((o1, o2) -> (int) (o2.getOrdersNo().compareTo(o1.getOrdersNo()))));
        }else{
            ordersList.sort(((o1, o2) -> (int) (o1.getOrdersNo().compareTo(o2.getOrdersNo()))));
        }

       List<String> movieImgList=new ArrayList<>();
        for (Orders orders1 : ordersList) {
            String movieName=orders1.getMovieName();
           movieImgList.add(movieDao.findMovieByName(movieName).getMovieImg());
        }
        model.addAttribute("movieImgList",movieImgList);
        model.addAttribute("orderList",ordersList);
        model.addAttribute("userId",userId);
        return "user-orders";
    }
    @GetMapping("/success")
    public String playsuccess(){
        orders.setState("已完成");
        Integer result=ordersService.updateOrdersState(orders.getOrdersNo());
        return "play-success";
    }

    @GetMapping("/error")
    public String playerror(){
        //return "/WEB-INF/404.jsp";
        return "404";
    }
    @RequestMapping("/admin/getOrdersInfo")
    @ResponseBody
    public Map<String,Object> getOrdersInfo(HttpServletRequest request){
        String page = request.getParameter("page");
        String pageSize = request.getParameter("limit");
        String params = request.getParameter("searchParams");
        String userName = null;
        String ordersNo=null;
        String state=null;
        //先转换成JSONObject类型
        if (null != params){
            JSONObject obj = JSONObject.parseObject(params);
            userName= obj.getString("userName");
            ordersNo = obj.getString("ordersNo");
            state = obj.getString("state");
        }
        System.out.println(""+userName);
        System.out.println(""+ordersNo);
        System.out.println(""+state);
        Map<String,Object> ordersMap=new HashMap<>();
        PageInfo<Orders> orders=ordersService.findOrdersByPage(page,pageSize,userName,ordersNo,state);
        orders.getList().forEach(e-> System.out.println(e));
        ordersMap.put("code",0);
        ordersMap.put("msg","查找成功");
        //数据总数
        ordersMap.put("count",orders.getTotal());
        ordersMap.put("data",orders.getList());
        return ordersMap;
    }
}
